package com.gla.market.fragments;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.gla.market.R;
import com.gla.market.activity.BeforeSearchActivity;
import com.gla.market.activity.Commodity_FYHActivity;
import com.gla.market.activity.Shop_FYHActivity;
import com.gla.market.adapter.FYH_CommodityAdapter;
import com.gla.market.adapter.FYH_ShopAdapter;
import com.gla.market.constant.Constants;
import com.gla.market.entity.Commodity;
import com.gla.market.entity.FYH_Shop;
import com.gla.market.utils.NetUtil;
import com.tencent.map.geolocation.TencentLocation;
import com.tencent.map.geolocation.TencentLocationListener;
import com.tencent.map.geolocation.TencentLocationManager;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

//首页
public class HomePage extends Fragment implements TencentLocationListener {
    private int who;
    private double la, lo;

    private TextView nowxy;

    private ImageView selectIV, shopimg, petimg, useimg;
    private Drawable graydw, pinkdw;
    private LinearLayout petlayout, uselayout, shoplayout;

    //推荐产品
    private GridView recommendProductGridView;

    //热评和推荐商品的两个进度条
    private ProgressBar recommendProgressBar;
    private FYH_ShopAdapter recommendProductGridViewAdapter;
    private FYH_CommodityAdapter cmAdapter;

    //一次请求到分页商品数据,热评商品List
    private List<FYH_Shop> listShop = new ArrayList<>();
    private List<Commodity> listpet = new ArrayList<>();
    private List<Commodity> listuse = new ArrayList<>();

    //下拉刷新的layout
    private SwipeRefreshLayout mRefreshLayout;

    //定义一个自己的context
    private Context mContext;

    //商店
    private Handler uiHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case -1:
                    //网络请求失败
                    Toast.makeText(mContext, "网络请求失败！", Toast.LENGTH_SHORT).show();
                    break;
                case 0:
                    //网络请求成功，但是返回状态为失败
                    Toast.makeText(mContext, "未登录！", Toast.LENGTH_SHORT).show();
                    break;
                case 2:
                    recommendProductGridViewAdapter = new FYH_ShopAdapter(HomePage.this.getContext(), listShop, lo, la);
                    recommendProductGridView.setAdapter(recommendProductGridViewAdapter);
                    //设置gridView点击事件
                    recommendProductGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            TextView tvid = view.findViewById(R.id.shop_id);
                            Intent intent = new Intent(getActivity(), Shop_FYHActivity.class);
                            //将对应的产品id传到详情界面
                            intent.putExtra("id", tvid.getText().toString());
                            startActivity(intent);
                        }
                    });
                    //停止显示加载动画，显示商品信息
                    recommendProgressBar.setVisibility(View.GONE);
                    recommendProductGridView.setVisibility(View.VISIBLE);
                    break;
                default:
                    break;
            }
            //判断刷新动画
            if (mRefreshLayout.isRefreshing()) {
                //停止动画
                mRefreshLayout.setRefreshing(false);
            }
        }
    };

    //宠物
    private Handler petHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case -1:
                    //网络请求失败
                    Toast.makeText(mContext, "网络请求失败！", Toast.LENGTH_SHORT).show();
                    break;
                case 0:
                    //网络请求成功，但是返回状态为失败
                    Toast.makeText(mContext, msg.obj == null ? "获取商店数据失败！" : msg.obj.toString(), Toast.LENGTH_SHORT).show();
                    break;
                case 2:
                    cmAdapter = new FYH_CommodityAdapter(HomePage.this.getContext(), listpet);
                    recommendProductGridView.setAdapter(cmAdapter);
                    //设置gridView点击事件
                    recommendProductGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            TextView tvid = view.findViewById(R.id.shop_id);
                            Intent intent = new Intent(getActivity(), Commodity_FYHActivity.class);
                            //将对应的产品id传到详情界面
                            intent.putExtra("id", tvid.getText().toString());
                            startActivity(intent);
                        }
                    });
                    //停止显示加载动画，显示商品信息
                    recommendProgressBar.setVisibility(View.GONE);
                    recommendProductGridView.setVisibility(View.VISIBLE);
                    break;
                default:
                    break;
            }
            //判断刷新动画
            if (mRefreshLayout.isRefreshing()) {
                //停止动画
                mRefreshLayout.setRefreshing(false);
            }
        }
    };

    //用品
    private Handler useHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case -1:
                    //网络请求失败
                    Toast.makeText(mContext, "网络请求失败！", Toast.LENGTH_SHORT).show();
                    break;
                case 0:
                    //网络请求成功，但是返回状态为失败
                    Toast.makeText(mContext, msg.obj == null ? "获取商店数据失败！" : msg.obj.toString(), Toast.LENGTH_SHORT).show();
                    break;
                case 2:
                    cmAdapter = new FYH_CommodityAdapter(HomePage.this.getContext(), listuse);
                    recommendProductGridView.setAdapter(cmAdapter);
                    //设置gridView点击事件
                    recommendProductGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            TextView tvid = view.findViewById(R.id.shop_id);
                            Intent intent = new Intent(getActivity(), Commodity_FYHActivity.class);
                            //将对应的产品id传到详情界面
                            intent.putExtra("id", tvid.getText().toString());
                            startActivity(intent);
                        }
                    });
                    //停止显示加载动画，显示商品信息
                    recommendProgressBar.setVisibility(View.GONE);
                    recommendProductGridView.setVisibility(View.VISIBLE);
                    break;
                default:
                    break;
            }
            //判断刷新动画
            if (mRefreshLayout.isRefreshing()) {
                //停止动画
                mRefreshLayout.setRefreshing(false);
            }
        }
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_homepage, null);
        //初始化控件
        initView(view);

        //转存context
        mContext = getActivity().getApplicationContext();
        graydw = ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.gray_card, null);
        pinkdw = ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.pink_card, null);

        shoplayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                recommendProgressBar.setVisibility(View.VISIBLE);
                recommendProductGridView.setVisibility(View.GONE);
                GetRandomBook();
                who = 1;
                shopimg.setBackground(pinkdw);
                useimg.setBackground(graydw);
                petimg.setBackground(graydw);
            }
        });

        petlayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                recommendProgressBar.setVisibility(View.VISIBLE);
                recommendProductGridView.setVisibility(View.GONE);
                GetPet();
                who = 2;
                shopimg.setBackground(graydw);
                useimg.setBackground(graydw);
                petimg.setBackground(pinkdw);
            }
        });

        uselayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                recommendProgressBar.setVisibility(View.VISIBLE);
                recommendProductGridView.setVisibility(View.GONE);
                GetUse();
                who = 3;
                shopimg.setBackground(graydw);
                useimg.setBackground(pinkdw);
                petimg.setBackground(graydw);
            }
        });

        shopimg.setBackground(pinkdw);
        //判断网络状态，并初始化数据
        if (NetUtil.isNetworkAvailable(getContext())) {
            //获取随机商品推荐
            getLocation();
        } else {
            //弹出一个框，提示网络不正常！
            Toast.makeText(getActivity().getApplicationContext(), "当前网络环境不正常，商品信息可能无法显示", Toast.LENGTH_LONG).show();
        }
        // 刷新监听。
        mRefreshLayout.setOnRefreshListener(mRefreshListener);
        return view;
    }

    public void getLocation(){
        //获取定位
        TencentLocationManager mLocationManager = TencentLocationManager.getInstance(mContext);
        mLocationManager.requestSingleFreshLocation(null, this, Looper.getMainLooper());
    }

    //刷新
    private SwipeRefreshLayout.OnRefreshListener mRefreshListener = new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            //获取随机商品数据
            getLocation();
            switch (who){
                case 1:
                    GetRandomBook();
                    break;
                case 2:
                    GetPet();
                    break;
                case 3:
                    GetUse();
                    break;
            }
        }
    };

    //获取商品
    private void GetRandomBook() {
        String url = Constants.BASE_URL + Constants.GET_FYH_SHOP_URL + Constants.GET_FYH_SHOPNEAR_URL + Constants.ulalo(la, lo);
        NetUtil.doGet(url, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.e("调试", "错误信息：" + e.toString());
                        Message message = Message.obtain();
                        message.what = -1;
                        uiHandler.sendMessage(message);
                    }
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String result = response.body().string().trim();
                        com.alibaba.fastjson.JSONObject object = JSON.parseObject(result);
                        Message message = Message.obtain();

                        if (!object.getString("message").contains("JWT") && object.getString("error")==null && object.getInteger("code")==100) {
                            JSONArray array = object.getJSONArray("data");
                            //获得商品list
                            listShop = JSONArray.parseArray(array.toString(), FYH_Shop.class);
                            message.what = 2;
                        } else {
                            message.what = 0;
                        }
                        uiHandler.sendMessage(message);
                    }
                }
        );
    }

    //获取宠物
    private void GetPet() {
        String url = Constants.BASE_URL + Constants.GET_FYH_SHOP_URL + Constants.GET_FYH_ALLCMBYPOU_URL + 0;
        NetUtil.doGet(url, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.e("调试", "错误信息：" + e.toString());
                        Message message = Message.obtain();
                        message.what = -1;
                        uiHandler.sendMessage(message);
                    }
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String result = response.body().string().trim();
                        com.alibaba.fastjson.JSONObject object = JSON.parseObject(result);
                        Message message = Message.obtain();

                        if (!object.getString("message").contains("JWT") && object.getString("error")==null && object.getInteger("code")==100) {
                            JSONArray array = object.getJSONArray("data");
                            //获得商品list
                            listpet = JSONArray.parseArray(array.toString(), Commodity.class);
                            message.what = 2;
                        } else {
                            message.what = 0;
                        }
                        petHandler.sendMessage(message);
                    }
                }
        );
    }

    //获取用品
    private void GetUse() {
        String url = Constants.BASE_URL + Constants.GET_FYH_SHOP_URL + Constants.GET_FYH_ALLCMBYPOU_URL + 1;
        NetUtil.doGet(url, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.e("调试", "错误信息：" + e.toString());
                        Message message = Message.obtain();
                        message.what = -1;
                        uiHandler.sendMessage(message);
                    }
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String result = response.body().string().trim();
                        com.alibaba.fastjson.JSONObject object = JSON.parseObject(result);
                        Message message = Message.obtain();

                        if (!object.getString("message").contains("JWT") && object.getString("error")==null && object.getInteger("code")==100) {
                            JSONArray array = object.getJSONArray("data");
                            //获得商品list
                            listuse = JSONArray.parseArray(array.toString(), Commodity.class);
                            message.what = 2;
                        } else {
                            message.what = 0;
                        }
                        useHandler.sendMessage(message);
                    }
                }
        );
    }

    /*初始化绑定控件*/
    public void initView(View view) {
        mRefreshLayout = view.findViewById(R.id.refresh_layout);
        who = 1;

        //绑定进度条
        recommendProgressBar = view.findViewById(R.id.recommend_progress);

        recommendProductGridView = view.findViewById(R.id.recommend_gridview);

        shopimg = view.findViewById(R.id.shopimg);
        petimg = view.findViewById(R.id.petimg);
        useimg = view.findViewById(R.id.useimg);

        shoplayout = view.findViewById(R.id.shoplayout);
        petlayout = view.findViewById(R.id.petlayout);
        uselayout = view.findViewById(R.id.uselayout);

        nowxy = view.findViewById(R.id.nowxy);

        selectIV = view.findViewById(R.id.selectIV);
        selectIV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), BeforeSearchActivity.class);
                startActivity(intent);
            }
        });
    }

    @Override
    public void onLocationChanged(TencentLocation tencentLocation, int i, String s) {
        la = tencentLocation.getLatitude();
        lo = tencentLocation.getLongitude();
        nowxy.setText(tencentLocation.getAddress());
        mRefreshListener.onRefresh();
    }

    @Override
    public void onStatusUpdate(String s, int i, String s1) { }
}
